﻿#include "ui.hpp"

using namespace rex;

Ui::Ui(){
	file_name = NULL;
	store = NULL;
}

Ui::~Ui(){
	if (store){
		delete store;
	}
}

// 打开文件
bool Ui::open(){
	FILE* fp = NULL;
	
	file_name = (char*)malloc(sizeof(char)*FILENAME_LEN);
	memset(file_name, 0, sizeof(char)* FILENAME_LEN);
	strncpy(file_name, "data.rex", 9);

	while (true)
	{
		fp = fopen(file_name, "rb+");
		if (fp == NULL)
		{
			int selected = 0;

			system("cls");
			cout<<red<<"文件不存在...\n"<<white;
			printf("===========\n");
			printf("0. 打开文件\n");
			printf("1. 创建文件\n");
			printf("===========\n");

			selected = get_int();
			if (selected == 0){
				size_t len = 0;
				printf("选择打开文件:");
				memset(file_name, 0, FILENAME_LEN);
				fgets(file_name, FILENAME_LEN - 1, stdin);
				len = strlen(file_name);
				if (file_name[0] == '"')
				{
					strncpy(file_name, file_name + 1, len - 2);
					file_name[len - 3] = '\0';
				}
				else{
					file_name[len - 1] = '\0';
				}
				fflush(stdin);
			}
			else if (selected == 1){
				// 新建文件
				fp = fopen(file_name, "ab+");
				BaseHeader header;

				memset(&header, 0, sizeof(BaseHeader));
				header.file_type = 0x520f;
				header.base_version = 0x01;
				header.date = 0x12345678;

				printf("是否加密[Y/N]: ");
				if ('Y' == get_char()){
					printf("请输入密码:");
					get_pwd(header.password, 40);
					header.is_encrypt = 0x01;
				}
				else{
					header.is_encrypt = 0x00;
				};

				fwrite(&header,sizeof(BaseHeader),1,fp);
				fflush(fp);
				fclose(fp);
				break;
			}

		}
		else{
			fclose(fp);
			break;
		}
	}

	try{
		store = new Store(file_name); // 创建Store对象
	}
	catch (const char*){
		cout << red << "打开文件类型错误: " << GetLastError() << white << endl;
		return false;
	}

	BaseHeader* header_for_login = store->get_header();
	bool login_result = false;
	size_t login_try_count = 0;

	if (header_for_login->is_encrypt){
		while (true){
			login_result = login("root", header_for_login->password);

			if (login_result){
				break;
			}
			else{
				++login_try_count;
				if (3 == login_try_count){
					cout << red << "\n已经尝试登陆3次，程序退出..." << white << endl;
					system("pause");
					exit(0);
				}
			}
		}
	}

	if (store){
		return true;
	}
	else{
		return false;
	}
	
}

void Ui::status(){
	BaseHeader* file_header = NULL;
	size_t num = 0;

	file_header = store->get_header();
	if (file_header){
		num = (size_t)file_header->record_number;
	}

	system("cls");
	cout << right;
	cout << "当前使用:" << green << setw(10) << Ui::file_name << yellow << num << "条" << white << endl;
	//cout << "================================================================================" << endl;
	cout << "--------------------------------------------------------------------------------" << endl;
	Ui::file_name;
}

void Ui::show_main(){
	int iChoose = -1;

	while (iChoose < 0 || iChoose > 4)
	{
		system("cls");

		this->status();
		printf("********学生信息管理系统********\n");
		printf("          1、 增加信息          \n");
		printf("          2、 删除信息          \n");
		printf("          3、 修改信息          \n");
		printf("          4、 查询信息          \n");
		printf("          0、 退出系统          \n");
		printf("********************************\n");
		printf("请输入您的选择：");
		iChoose = get_int();

	}

	switch (iChoose)
	{
	case 1:
		show_add(); // 添加学生
		break;
	case 2:
		show_delete();
		break;
	case 3:
		show_change();
		break;
	case 4:
		show_search();
		break;
	case 0:
		delete store;
		system("pause");
		exit(0);
		break;
	default:
		break;
	}
}

void Ui::show_delete(){
	int stu_number = 0;
	char buffer[20];

	status();
	printf("请输入要删除的学生学号:");
	memset(buffer, 0, 20);
	get_string(buffer,19);
	stu_number = atoi(buffer);
	Node* node = store->search_student(stu_number);
	if (!node){
		printf("学生不存在！\n");
		return;
	}
	if (!node->student){
		printf("学生不存在！\n");
		return;
	}
	show_student(node->student);
	if (store->delete_student(node)){
		printf("删除成功\n");
	}
	else{
		printf("删除失败\n");
	}
}

void Ui::show_change(){
	char buffer[20];
	int stu_number = 0;
	bool result = false;

	status();
	printf("请输入要修改的学生的学号:");
	memset(buffer,0,20);
	get_string(buffer, 19);
	stu_number = atoi(buffer);

	// get
	Node* node = store->search_student(stu_number);
	// delete
	if (!node){
		return;
	}
	if (!node->student){
		return;
	}
	result = store->delete_student(node);

	// add
	this->show_add();
}

void Ui::show_search(){
	int choose = 0;
	char buffer[20];
	int stu_number = 0;
	Node* node;

	while(true){
		status();
		printf("==================================\n");
		printf("1、按姓名查询\n");
		printf("2、按学号查询\n");
		printf("==================================\n");
		printf("请选择:");
		choose = get_int();
		if (1 == choose){
			printf("请输入学生姓名:");
			memset(buffer, 0, 20);
			get_string(buffer,19);
			node = store->search_student(buffer);
			if (!node){
				printf("未找到\n");
				continue;
			}
			if (node->student){
				show_student(node->student);
				break;
			}
			else{
				continue;
			}
		}else if (2 == choose){
			printf("请输入学生学号:");
			memset(buffer, 0, 20);
			get_string(buffer, 19);
			stu_number = atoi(buffer);
			node = store->search_student(stu_number);
			if (!node){
				printf("未找到\n");
				continue;
			}
			if (node->student){
				show_student(node->student);
				break;
			}
			else{
				continue;
			}
		}else{
			continue;
		}
	}
	

}

void Ui::show_add(){
	Student stu;
	char buffer[50];

	memset(&stu, 0, sizeof(Student));
	system("cls");

	this->status();
	printf("**********添加学生信息**********\n");
	
	while (true){
		int result = 0;
		
		cout << "学号：";
		memset(buffer, 0, 50);
		get_string(buffer, 20);
		result = atoi(buffer);
		if (result > 0){
			stu.stu_number = result;
			break;
		}
	}

	cout << "姓名：";
	get_string(stu.stu_name,20);

	while (true){
		int result = 0;
		cout << "性别[M/F]：";
		result = get_char();
		if (result == 'M'){
			stu.stu_sex = 0x01;
			break;
		}
		else if(result == 'F'){
			stu.stu_sex = 0x00;
			break;
		}
		else{
			continue;
		}
	}
	
	while (true){
		int result = 0;

		cout << "年龄：";
		memset(buffer, 0, 50);
		get_string(buffer, 4);
		result = atoi(buffer);
		if (result > 0){
			stu.stu_age = result;
			break;
		}
	}
	
	while (true){
		int result = 0;

		cout << "电话：";
		memset(buffer, 0, 50);
		get_string(buffer, 12);
		strncpy(stu.stu_phone, buffer, strlen(buffer));
		break;
	}

	while (true){
		int result = 0;

		cout << "籍贯：";
		memset(buffer, 0, 50);
		get_string(buffer, 5);
		strncpy(stu.stu_province, buffer, strlen(buffer));
		break;
	}

	while (true){
		int result = 0;

		cout << "地址1：";
		memset(buffer, 0, 50);
		get_string(buffer, 50);
		strncpy(stu.stu_address1, buffer, strlen(buffer));
		break;
	}

	while (true){
		int result = 0;

		cout << "地址2：";
		memset(buffer, 0, 50);
		get_string(buffer, 50);
		strncpy(stu.stu_address2, buffer, strlen(buffer));
		break;
	}

	while (true){
		int result = 0;

		cout << "地址3：";
		memset(buffer, 0, 50);
		get_string(buffer, 50);
		strncpy(stu.stu_address3, buffer, strlen(buffer));
		break;
	}

	store->add_student(&stu);
	
}

// 键盘获取int
int Ui::get_int(){
	char buffer[10];

	fgets(buffer, 9, stdin);
	fflush(stdin);
	if (buffer[0] >= '0' && buffer[0] <= '9'){
		return buffer[0] - '0';
	}
	else{
		return -1;
	}
}

// 键盘获取char
char Ui::get_char(){
	char buffer[10];

	fgets(buffer, 9, stdin);
	_strupr(buffer);
	fflush(stdin);
	if (buffer[0] >= 'A' && buffer[0] <= 'Z'){
		return buffer[0];
	}
	else{
		return -1;
	}
}

bool Ui::login(char* username, char* password){
	char input_username[20];
	char input_password[40];
	bool result_username = false;
	bool result_password = false;
	
	memset(input_username, 0, 20);
	memset(input_password, 0, 40);

	system("cls");
	printf("*******登录学生信息管理系统******\n");
	printf("用户名: ");
	get_string(input_username,19);
	
	printf("密  码: ");
	get_pwd(input_password, 40);
	
	result_username = !strcmp(username, input_username);
	result_password = !strcmp(password, input_password);
	
	if (result_username && result_password){
		return true;
	}
	else{
		return false;
	}

}

// 从键盘输入密码
void Ui::get_pwd(char* password,size_t len){
	int  i = 0;
	int  ch = 0;
	bool skip = false;

	while ('\r' != (ch = getch())){
		
		if (skip){
			skip = false;
			continue;
		}

		if (224 == ch){ // control
			skip = true;
			continue;
		}

		if (8 == ch){ //backspace
			if (i == 0){
				printf("\7");
				continue;
			}
			printf("\b \b");
			password[i] = 0;
			i--;
			continue;
		}

		if (i >= len - 1){
			printf("\7");
			continue;
		}
		
		if (224 != ch)
		{
			password[i] = ch;
			printf("*");
			i++;
		}
		else{
			printf("%d", ch);
		}
	}
}

// 从键盘输入string
void Ui::get_string(char* str, size_t len){
	fgets(str, len, stdin);
	if (str[strlen(str) - 1] == '\n'){
		str[strlen(str) - 1] = 0;
	}
	str[len - 1] = 0;
	fflush(stdin);
}

// 显示学生信息
void Ui::show_student(Student* stu){
	if (stu == NULL){
		return;
	}
	else{
		cout << "学号：" << yellow << (int)stu->stu_number << white << endl;
		cout << "姓名：" << yellow << (char*)stu->stu_name << white << endl;
		cout << "性别：" << yellow << (char*)(stu->stu_sex ? "男" : "女") << white << endl;
		cout << "年龄：" << yellow << (int)stu->stu_age << white << endl;
		cout << "电话：" << yellow << (int)stu->stu_phone << white << endl;
		cout << "籍贯：" << yellow << (char*)stu->stu_province << white << endl;
		cout << "地址1：" << yellow << (char*)stu->stu_address1 << white << endl;
		cout << "地址2：" << yellow << (char*)stu->stu_address2 << white << endl;
		cout << "地址3：" << yellow << (char*)stu->stu_address3 << white << endl;
		system("pause");
	}
}
